package com.cy.src.weex;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Pattern;

/**
 * Created by CY on 2017/1/9.
 * <p>
 * 使用java 命令编译，需要删除包名
 */

public class EmailHandler {

    public static void main(String args[]) throws IOException {

        if (args == null || args.length < 1) {
            throw new IllegalArgumentException("参数不合法，请输入文件路径");
        }


        handlerFile(args[0]);
    }


    private static void handlerFile(String inputPath) throws IOException {
        File file = new File(inputPath);

        if (!file.exists()) {
            throw new IllegalArgumentException("参数不合法，输入文件不存在");
        }

        if (file.isFile()) {
            String outPath = file.getParent() + File.separator + "QQEmail_" + file.getName();
            read(inputPath, outPath);
        } else if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File ip : files) {
                String outPath = ip.getParent() + File.separator + "QQEmail_" + ip.getName();
                read(ip.getPath(), outPath);
            }
        }


    }


    private static void read(String path, String outPath) throws IOException {
        FileInputStream fis = new FileInputStream(path);

        FileOutputStream fos = new FileOutputStream(outPath);

        BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

        String line;

        String name = null;

        while ((line = reader.readLine()) != null) {

            if (line.trim().isEmpty()) {
                continue;
            }

            int startIndex = line.indexOf('(');
            int lastIndex = line.lastIndexOf(')');
            if (startIndex != -1 && lastIndex != -1 && startIndex != lastIndex) {

                String qq = line.substring(startIndex + 1, lastIndex);

                if (Pattern.matches("^[0-9]*$", qq)) {

                    String qqEmail = qq + "@qq.com";
                    String out = name + "\t\t\t" + qqEmail;
                    System.out.println(out);
                    fos.write((out).getBytes());
                    fos.write('\n');
                } else {
                    name = qq;
                }
            } else {

                name = line;
            }
        }

        fos.flush();
        fis.close();
        fos.close();
        reader.close();

    }


}
